<template>
    <div class="category">
        <el-button type="primary" @click="handleAdd">新增项目类别</el-button>
        <el-table :data="categories" stripe class="main-table" size="small" height="calc(100vh - 196px)">
            <!-- <el-table-column label="ID" prop="id" width="70" align="center" /> -->
            <el-table-column prop="name" label="类别名" min-width="150" align="center" />
            <el-table-column prop="description" label="类别描述" min-width="200" align="left" />
            <el-table-column prop="created_at" label="创建时间" width="155" align="center" />
            <el-table-column label="操作" width="130" align="center" fixed="right">
                <template #default="{ row, $index }">
                    <div class="operate">
                        <el-link type="primary" :underline="false" @click="reorder(-1, row)" title="上移"
                            :disabled="$index == 0 && page == 1">↑</el-link>
                        <el-link type="primary" :underline="false" @click="reorder(1, row)" title="下移"
                            :disabled="(page - 1) * pageSize + $index + 1 >= total">↓</el-link>
                        <el-link type="primary" :underline="false" @click="handleEdit(row)">编辑</el-link>
                        <el-link type="danger" :underline="false" @click="handleDelete(row.id)">删除</el-link>
                    </div>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination background :page-sizes="[10, 20, 50]" @change="pageChange"
            layout="total, prev, pager, next, sizes" :total="total" />
        <el-drawer v-model="drawer" direction="rtl" size="300" :before-close="resetForm" :show-close="true"
            :wrapperClosable="true">
            <el-form :model="category" ref="categoryForm" :rules="rules" label-width="80px" :inline="false">
                <el-form-item label="ID" v-if="category.id" prop="id">
                    <el-input v-model="category.id" disabled></el-input>
                </el-form-item>
                <el-form-item label="类别名称" prop="name">
                    <el-input v-model="category.name"></el-input>
                </el-form-item>
                <!-- <el-form-item label="启动命令" prop="command" v-if="!category.id">
                    <el-input v-model="category.command" placeholder="本地开发启动命令"></el-input>
                </el-form-item> -->
                <el-form-item label="描述" prop="description">
                    <el-input v-model="category.description"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="onSubmit">保存</el-button>
                    <el-button @click="resetForm">取消</el-button>
                </el-form-item>
            </el-form>
        </el-drawer>
    </div>
</template>

<script setup lang="ts">
import database from '@/api/database'
import { ElMessage } from 'element-plus'

type CategoryNew = { id?: number, name: string, description?: string, command?: string }

const categories = ref<Category[]>([])
const category = ref<CategoryNew>({ name: '', description: '' })
const total = ref(0)
const drawer = ref(false)
const form = useTemplateRef('categoryForm')
const rules = reactive({
    name: [
        { required: true, message: '请输入类别名称', trigger: 'blur' },
        { min: 1, max: 20, message: '长度在20个字符内', trigger: 'blur' },
    ],
    description: [
        { min: 1, max: 50, message: '长度在50个字符内', trigger: 'blur' },
    ],
    // command: [
    //     { required: true, message: '请输入启动命令', trigger: 'blur' },
    //     { min: 1, max: 200, message: '长度在200个字符内', trigger: 'blur' },
    // ],
})
const page = ref(1)
const pageSize = ref(10)

function onSubmit() {
    form.value?.validate(async (valid: boolean) => {
        if (valid) {
            if (category.value?.id) {
                // 更新
                (await database()).table('categories').where('id', category.value.id).update(category.value).then(() => {
                    resetForm()
                    getCategories()
                    ElMessage.success('更新成功')
                }).catch(err => {
                    ElMessage.error(err)
                })
            } else {
                // 新增...新增同时创建命令?
                await (await database()).table('categories').create({ name: category.value.name, description: category.value.description }).then(() => {
                    // (await database()).table('commands').create({ name: '启动', command: category.value.command, category_id: res, description: '本地开发启动命令' }).then(() => {
                    resetForm()
                    getCategories()
                    ElMessage.success('操作成功')
                    // }).catch(async err => {
                    //     await (await database()).table('categories').delete(res)
                    //     ElMessage.error(err)
                    // })
                }).catch(err => {
                    ElMessage.error(err)
                })
            }
        }
    })
}
function handleAdd() {
    category.value = { name: '', description: '' }
    drawer.value = true
}
function handleEdit(row: Category) {
    category.value = { ...row }
    drawer.value = true
}
async function handleDelete(id: number) {
    (await database()).table('projects').where("category_id", id).find<Project>().then(async res => {
        if (res) {
            ElMessage.error('请先删除该类别下的项目')
            return
        }
        (await database()).table('categories').delete(id).then(res => {
            if (res == 1) {
                ElMessage.success('操作成功')
                getCategories()
            } else {
                ElMessage.error('没有数据被删除')
            }
        }).catch(err => {
            ElMessage.error(err)
        })
    }).catch(err => {
        ElMessage.error(err)
        return
    })
}
function resetForm() {
    form.value?.resetFields()
    drawer.value = false
}
function pageChange(p: number, ps: number) {
    page.value = p
    pageSize.value = ps
    getCategories()
}
async function getCategories() {
    (await database()).table('categories').orderBy('sort', 'asc').paginate<Category>(page.value, pageSize.value).then(res => {
        categories.value = res.data
        total.value = res.total
        console.log(res)
    }).catch(err => {
        ElMessage.error(err)
    })
}
async function reorder(direction: number, row: Category) {
    // let targetIndex = (page.value - 1) * pageSize.value + index + direction
    // const target = categories.value[targetIndex]
    // const sort = target.sort
    let target = await (await database()).table('categories').where('sort', direction > 0 ? '>' : '<', row.sort).orderBy('sort', direction > 0 ? 'asc' : 'desc').find<Category>()
    if (target != null) {
        await (await database()).table('categories').where('id', target.id!).update({ sort: row.sort })
        await (await database()).table('categories').where('id', row.id!).update({ sort: target.sort })
    }
    getCategories()
}

onMounted(() => {
    // 获取数据
    getCategories()
})
</script>

<style lang="scss" scoped></style>